package com.cat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cat.common.ImgState;
import com.cat.mybatis.dao.ImgSourceDao;
import com.cat.mybatis.domain.ImgSourceDO;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.xml.ws.Response;
import java.io.IOException;
import java.util.*;

@Service
public class AnalyzeService {


    public static final String CAT_NAME_STR = "egyptiancat|persiancat|kitty|kittycat|puss|pussy|pussycat|tigercat|angora|angoracat|tom|tomcat|siamesecat|siamese|manx|manxcat|maltese|maltesecat|tabby|queen|burmesecat|alleycat|abyssinian|abyssiniancat|tabby|tabbycat|tortoiseshell|tortoiseshellcat|calicocat|mouser";
    public static final String ANALYZE_URL = "http://bigcat.natapp1.cc";
    public static final int countPerRequest = 2;



    @Resource
    ImgSourceDao imgSourceDao;

    private Set<String> catNameSet = new TreeSet<>();

    public AnalyzeService(){
        for(String x: CAT_NAME_STR.split("\\|")){
            catNameSet.add(x);
        }

    }

    private boolean isCat(String name){
        return catNameSet.contains(name.replaceAll("[ _\\-]","").toLowerCase());
    }

    /**
     * post 到分析服务器，接受返回结果，入库
     */
    public void analyzeImg() throws IOException {

        List<ImgSourceDO> list = imgSourceDao.selectByState(ImgState.Init.getCode());
        List<RequestDataVO> allReqData = new ArrayList<>();



        list.stream().limit(countPerRequest).forEach(x->{
            RequestDataVO imgReqData = new RequestDataVO();
            imgReqData.setImgPath(x.getUrl());
            imgReqData.setId(x.getImgId().toString());
            allReqData.add(imgReqData);
        });

        System.out.println("【AnalyzeService】req img count:"+allReqData.size());

        if(allReqData.size() == 0){
            System.out.println("【AnalyzeService】abort");
            return;
        }
        //请求
        List<ReturnDataVO> ans = doPost(ANALYZE_URL,allReqData);



        if(ans!=null){
            //入库
            for(ReturnDataVO x:ans){
                //判断是否为猫
                boolean isCatAns = isCat(x.getResult());
                if(isCatAns){
                    imgSourceDao.updateState(ImgState.Analyzed.getCode(),Integer.parseInt(x.getId()));
                }else{
                    imgSourceDao.updateState(ImgState.AnalyzedNotCat.getCode(),Integer.parseInt(x.getId()));
                }

                System.out.println("id:"+Integer.parseInt(x.getId())+"[result:"+x.getResult()+"[isCat:"+isCatAns);
            }
        }else{
            System.out.println("【AnalyzeService】post failure");
        }

    }

    private RestTemplate restTemplate = new RestTemplate();
    private List<ReturnDataVO> doPost(String url, List<RequestDataVO> requestData) throws IOException {
        JSONObject jsonParam = new JSONObject();

        JSONArray imgUrl = new JSONArray();
        for (RequestDataVO requestDataVO:requestData
        ) {
            imgUrl.add(JSON.toJSON(requestDataVO));
        }

        jsonParam.put("picsList", imgUrl);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(jsonParam.toString(),headers);
        ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.POST, entity,String.class);

        List<ReturnDataVO> ans = new ArrayList<>();
        if (resp.getStatusCodeValue() == 200) {
            String respContent = resp.getBody();
            JSONObject resultObj =  JSONObject.parseObject(respContent);
            JSONArray array = (JSONArray) resultObj.get("resultsList");
            array.forEach(x->{
                JSONObject obj = (JSONObject) x;
                ans.add(obj.toJavaObject(ReturnDataVO.class));
            });
            return ans;
        }else {
            //fail
            System.out.println("【AnalyzeService】 error code "+resp.getStatusCode());
            return null;
        }

    }


    private static class RequestDataVO{
        String id;
        String imgPath;

        public String getId() {
            return id;
        }

        public String getImgPath() {
            return imgPath;
        }

        public void setId(String id) {
            this.id = id;
        }

        public void setImgPath(String imgPath) {
            this.imgPath = imgPath;
        }

        @Override
        public String toString() {
            return "RequestDataVO{" +
                    "id='" + id + '\'' +
                    ", imgPath='" + imgPath + '\'' +
                    '}';
        }
    }

    private static class ReturnDataVO{
        String id;
        String result;

        public void setId(String id) {
            this.id = id;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public String getId() {
            return id;
        }

        public String getResult() {
            return result;
        }

        @Override
        public String toString() {
            return "ReturnDataVO{" +
                    "id='" + id + '\'' +
                    ", result='" + result + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws Exception {
        List<RequestDataVO> imgUrl = new ArrayList<>();

        RequestDataVO vo1 = new RequestDataVO();
        vo1.setId("1");
        vo1.setImgPath("http://img.zcool.cn/community/01bc01566973b432f875a528ec7d39.jpg@2o.jpg");

        RequestDataVO vo2 = new RequestDataVO();
        vo2.setId("2");
        vo2.setImgPath("http://img.zcool.cn/community/01fdbd59102f7ca801216a3eeae036.jpg@1280w_1l_2o_100sh.jpg");

        imgUrl.add(vo1);
        imgUrl.add(vo2);
        AnalyzeService service = new AnalyzeService();
        service.doPost(ANALYZE_URL, imgUrl).forEach(x->{
            System.out.println(x.toString()+"is cat?"+service.isCat(x.getResult()));
        });


    }


}



